七日打卡 您所在的位置:网站首页 push strategy的例子 七日打卡

七日打卡

2024-02-11 22:39| 来源: 网络整理| 查看: 265

在Vue2.0路由跳转中,除了使用 创建 a 标签来定义导航链接,我们还可以借助 router 的实例方法,通过编写代码来实现。

router.push(location)

想要导航到不同的 URL,则使用 router.push 方法。这个方法会向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。

当你点击 时,这个方法会在内部调用,所以说,点击 等同于调用 router.push(...)。

声明式: 编程式:router.push(...)

该方法的参数可以是一个字符串路径,或者一个描述地址的对象。

// 字符串 router.push('home') // 对象 this.$router.push({path: '/login?url=' + this.$route.path}); // 命名的路由 router.push({ name: 'user', params: { userId: 123 }}) // 带查询参数,变成/backend/order?selected=2 this.$router.push({path: '/backend/order', query: {selected: "2"}}); // 设置查询参数 this.$http.post('v1/user/select-stage', {stage: stage}) .then(({data: {code, content}}) => { if (code === 0) { // 对象 this.$router.push({path: '/home'}); }else if(code === 10){ // 带查询参数,变成/login?stage=stage this.$router.push({path: '/login', query:{stage: stage}}); } }); // 设计查询参数对象 let queryData = {}; if (this.$route.query.stage) { queryData.stage = this.$route.query.stage; } if (this.$route.query.url) { queryData.url = this.$route.query.url; } this.$router.push({path: '/my/profile', query: queryData});

设置 replace 属性的话,当点击时,会调用 router.replace() 而不是 router.push(),于是导航后不会留下 history 记录。即使点击返回按钮也不会回到这个页面。

//加上replace: true后,它不会向 `history` 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。 this.$router.push({path: '/home', replace: true}) //如果是声明式就是像下面这样写: // 编程式: router.replace(...)

综合案例

this.$router.push({path: '/coach/' + this.$route.params.id, query: queryData}); 点击返回上一页 goback methods:{ goback(){ this.$router.go(-1) } }

点击跳转到/Foo2页面

goback ToLink1(){ this.$router.push('/foo2') }

或者this.$router.push({name:'Foo2'})对象的方法。

拓展阅读 vue路由传参的几种基本方式 1、动态路由(页面刷新数据不丢失) methods:{ insurance(id) { //直接调用$router.push 实现携带参数的跳转 this.$router.push({ path: `/particulars/${id}`, }) }

路由配置

{ path: '/particulars/:id', name: 'particulars', component: particulars }

接收页面通过 this.$route.params.id 接收

2、路由 name 匹配,通过params传参 methods:{ insurance(id) { this.$router.push({ name: 'particulars', params: { id: id } }) }

路由配置

{ path: '/particulars', name: 'particulars', component: particulars }

也是通过 this.$route.params.id 接收参数

3、路由path路径匹配,

通过query来传递参数,这种情况下 query传递的参数会显示在url后面?id=?

methods:{ insurance(id) { this.$router.push({ path: '/particulars', query: { id: id } }) }

路由配置

{ path: '/particulars', name: 'particulars', component: particulars }

通过 this.$route.query.id 接收参数

再次梳理下params传参和query传参的差别:

用法上

  刚才已经说了,query要用path来引入,params要用name来引入,接收参数都是类似的,分别是this.$route.query.name和this.$route.params.name。

PS:注意接收参数的时候,已经是$route而不是$router!

展示上

query更加类似于我们ajax中get传参,params则类似于post,说的再简单一点,前者在浏览器地址栏中显示参数,后者则不显示。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有